#include <stdio.h>
#include <dlfcn.h>

#include "capture_platform.h"

static int soc_api_check(capture_api_t *api);
static int decoder_camera_api_check(capture_api_t *api);
static int api_check(captrure_device_type_t dev_type, capture_api_t *api);

static int soc_api_check(capture_api_t *api)
{
	if (api->capture_create_buffers
		&& api->capture_create_context
		&& api->capture_destroy_context
		&& api->capture_get_frame
		&& api->capture_get_property_i
		&& api->capture_get_property_p
		&& api->capture_is_property
		&& api->capture_release_frame
		&& api->capture_set_property_i
		&& api->capture_set_property_p
		&& api->capture_update) {
		return 0;
	}

	return -1;
}

static int decoder_camera_api_check(capture_api_t *api)
{
	if (api->capture_create_context
		&& api->capture_destroy_context
		&& api->capture_get_property_i
		&& api->capture_get_property_p
		&& api->capture_is_property
		&& api->capture_set_property_i
		&& api->capture_set_property_p
		&& api->capture_update) {
		return 0;
	}

	return -1;
}

static int api_check(captrure_device_type_t dev_type, capture_api_t *api)
{
	switch(dev_type) {
	case CAPTURE_DEV_TYPE_SOC:
		return soc_api_check(api);
	case CAPTURE_DEV_TYPE_DECODER_CAMERA:
		return decoder_camera_api_check(api);
	default:
		printf("unknown device type\n");
		return -1;
	}
}

int capture_get_device_api(const char *lib_name, captrure_device_type_t dev_type, capture_api_t *api)
{
	void *handle = dlopen(lib_name, RTLD_LOCAL);
	if(!handle) {
		printf("dlopen %s error: %s\n", lib_name, dlerror());
		goto error_lib;
	}

	api->capture_create_buffers = dlsym(handle, "capture_create_buffers");
	api->capture_create_context = dlsym(handle, "capture_create_context");
	api->capture_destroy_context = dlsym(handle, "capture_destroy_context");
	api->capture_get_frame = dlsym(handle, "capture_get_frame");
	api->capture_get_property_i = dlsym(handle, "capture_get_property_i");
	api->capture_get_property_p = dlsym(handle, "capture_get_property_p");
	api->capture_is_property = dlsym(handle, "capture_is_property");
	api->capture_release_frame = dlsym(handle, "capture_release_frame");
	api->capture_set_property_i = dlsym(handle, "capture_set_property_i");
	api->capture_set_property_p = dlsym(handle, "capture_set_property_p");
	api->capture_update = dlsym(handle, "capture_update");
	api->capture_get_reg = dlsym(handle, "capture_get_reg");

	if (api_check(dev_type, api) != 0) {
		printf("api type %d check error\n", dev_type);
		goto error_api;
	}

	return 0;

error_api:
	dlclose(handle);

error_lib:
	return -1;
}
